/***************************************
 * @update: 2020-04-20  LiLinBin  [二次封装axios]
 * @update: xx  xx  [xx]
 * 
 * @description: axios的二次封装,设置请求拦截和响应拦截
 ***************************************/

import axios from 'axios'

axios.defaults.baseURL = process.env.BASE_URL || '/'
axios.defaults.withCredentials = false //关掉跨域令牌
axios.defaults.timeout = 1 * 60 * 1000



let curUrl = ''



//请求拦截
axios.interceptors.request.use(
    function (config) {
        return config
    },
    function (error) {
        return Promise.reject(error.toString())
    }
)



//响应拦截
axios.interceptors.response.use(
    successRes,
    function (err) {
        const response = err.response || {}
        if (response.status === 500 && response.data) {
            return successRes(response)
        }

        errFn(curUrl, err)
        return null
    }
)




//成功的响应
function successRes (response) {
    const { url } = response.config
    curUrl = url

    try {
        if (url.indexOf('/mock') === 0) return response.data || {}
        return response
    } catch (err) {
        errFn(url, err)
        return null
    }
}





function errFn (url, err) {
    console.error(`接口异常: ${url}; \n 错误信息为: \n ${err.toString()}`)
}








export default axios